# encoding:utf-8
import requests as req;
import base64;


# https://cloud.baidu.com/doc/OCR/s/zk3h7xz52
APPID = '23619516';
APIKEY = 'X7iS2qiuOKx2pUC8Z9gfOF68';
SECRETKEY = 'jXBAbD5uxUG9zhn5RcRR0x4pKvsU1swH';

# 获取Access Token
def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token";
    params = {
        "grant_type":"client_credentials",
        "client_id":APIKEY,
        "client_secret":SECRETKEY,
    }

    json = req.post(url=url,params=params).json();

    if json.get("access_token"):
        return json.get("access_token");


# 通用文字识别（高精度版）
def img_to_word(img_path):

    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
    # 二进制方式打开图片文件
    with open(img_path, 'rb') as rf:
        img = base64.b64encode(rf.read());

    params = {
        "image":img,
        "access_token": get_access_token()
    }

    # url = url + "?access_token=" + get_access_token()
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = req.post(url=url,data=params,headers=headers);

    print(response.json());
    if response:
        print (response.json().get("words_result"))




if __name__ == '__main__':

    img_to_word("code.png")

